<template>
  <div class="card-wrap flex-column justify-end card-padding">
    <el-form :model="form" ref="carInformation" label-width="100px">
      <div class="card-title-wrap">
        <span>车辆信息</span>
        <span></span>
      </div>
      <div v-if="type !=='detail' && form.receivingInfo==1" style="display: flex; justify-content: space-between; align-items: center;flex-wrap: wrap;width: 70%;margin-top: 20px;">
        <div style="min-Width:43%;display: flex;flex-wrap: wrap;justify-content: start;align-items: center;">
          <el-form-item label="公里数:" prop="aaaa" style="width: 80%;">
            <el-input :disabled="form.carList && form.carList.length == 0" style="width: 100%;margin-right: 10px;" v-model="form.aaaa" :placeholder="form.carList && form.carList.length == 0?'请先选择车辆':'此字段用于快速填充数据'"></el-input>
          </el-form-item>
          <el-button :disabled="form.carList && form.carList.length == 0" type="text" @click="changeValue(1)" style="margin-top: -20px;font-size: 14px;margin-left: 10px;">一键填入</el-button>
        </div>
        <div style="min-Width:43%;display: flex;flex-wrap: wrap;justify-content:start;align-items: center;">
          <el-form-item label="仓储天数:" prop="bbbb" style="width: 80%;">
            <el-input :disabled="form.carList && form.carList.length == 0" style="width: 100%;margin-right: 10px;" v-model="form.bbbb" :placeholder="form.carList && form.carList.length == 0?'请先选择车辆':'此字段用于快速填充数据'"></el-input>
          </el-form-item>
          <el-button :disabled="form.carList && form.carList.length == 0" type="text" @click="changeValue(2)" style="margin-top: -20px;font-size: 14px;margin-left: 10px;">一键填入</el-button>
        </div>
      </div>
      <div v-if="type !=='detail'" style="display: flex; justify-content: space-between; align-items: center;flex-wrap: wrap;width: 70%;">
        <div style="min-Width:43%;display: flex;flex-wrap: wrap;justify-content: start;align-items: center;">
          <el-form-item label="收车地址:" prop="cccc" style="width: 80%;">
            <el-input :disabled="form.carList && form.carList.length == 0" style="width: 100%;margin-right: 10px;" v-model="form.cccc" :placeholder="form.carList && form.carList.length == 0?'请先选择车辆':'此字段用于快速填充数据'"></el-input>
          </el-form-item>
          <el-button :disabled="form.carList && form.carList.length == 0" type="text" @click="changeValue(3)" style="margin-top: -20px;font-size: 14px;margin-left: 10px;">一键填入</el-button>
        </div>
        <div style="min-Width:43%;display: flex;flex-wrap: wrap;justify-content: start;align-items: center;">
          <el-form-item label="送车地址:" prop="dddd" style="width: 80%;">
            <el-input :disabled="form.carList && form.carList.length == 0" style="width: 100%;margin-right: 10px;" v-model="form.dddd" :placeholder="form.carList && form.carList.length == 0?'请先选择车辆':'此字段用于快速填充数据'"></el-input>
          </el-form-item>
          <el-button :disabled="form.carList && form.carList.length == 0" type="text" @click="changeValue(4)" style="margin-top: -20px;font-size: 14px;margin-left: 10px;">一键填入</el-button>
        </div>
      </div>
      <div class="table-title-wrap flex-row-center" style="margin-top: 20px">
        <p class="statisticInfo">本次收回车辆数: <span>{{ form.carList && form.carList.length }} 台</span></p>
        <p class="statisticInfo" v-if="type !=='detail' &&form.receivingInfo==1">总费用: <span>{{format_thousand(totalPrice)}} 元</span></p>
      </div>
      <el-button v-if="type !== 'detail'" type="text" style="margin-left: 5px;font-size: 14px;" @click="selectCar">选择车辆</el-button>
      <el-table :data="form.carList" border>
        <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" v-if="type !== 'detail'">
          <template slot-scope="{row,$index}">
            <el-button type="text" @click="selectCustomer(row,$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="车牌号" align="center" prop="carNo" min-width="120px" show-overflow-tooltip />
        <el-table-column label="车架号" align="center" prop="vinNo" min-width="120px" show-overflow-tooltip />
        <el-table-column label="品牌/车型/车款" align="center" prop="carInFo" min-width="360px" show-overflow-tooltip />
        <el-table-column label="车辆归属" align="center" prop="vehicleOwnerName" min-width="120px" show-overflow-tooltip />
        <el-table-column label="额度申请编号" align="center" prop="calcSchemeCode" min-width="200px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span @click="goToDetail(scope.row.calcSchemeId, scope.row.processId)" style="color: #1890ff; cursor: pointer">{{ scope.row.calcSchemeCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单编号" align="center" prop="orderCarCode" min-width="200px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span @click="orderDetail(scope.row)" style="color: #1890ff; cursor: pointer">{{ scope.row.orderCarCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出租方" align="center" prop="lessorName" min-width="120px" show-overflow-tooltip />
        <el-table-column label="业务类型" align="center" prop="businessType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.business_type" :value="scope.row.businessType" />
          </template>
        </el-table-column>
        <el-table-column label="订单提交人" align="center" prop="orderSubmitter" min-width="120px" show-overflow-tooltip />
        <el-table-column label="GPS状态" align="center" prop="gpsStatus" min-width="120px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-if="type !== 'detail'" v-model="scope.row.gpsStatus" placeholder="请选择">
              <el-option v-for="item in GPSlist" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <span v-if="type == 'detail'">{{scope.row.gpsStatus==1?'正常':'异常'  }}</span>
          </template>
        </el-table-column>

        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="服务费(元)" align="center" prop="serviceCharge" min-width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.serviceCharge" maxlength="11" @input="scope.row.serviceCharge=scope.row.serviceCharge.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" placeholder="请输入服务费" />
          </template>
        </el-table-column>
        <TableCloumn v-if="form.receivingInfo==1 && type !== 'detail' " v-for="item in tableCloumnGLS" :cellOptions="item" minWidth="150px" />

        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="运输费单价(元/公里/台)" align="center" prop="unitPriceOfFreight" min-width="200px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ format_thousand(scope.row.unitPriceOfFreight) }}</span>
          </template>
        </el-table-column>

        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="运输费" align="center" prop="priceOfFreight" min-width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.priceOfFreight" maxlength="11" @input="scope.row.priceOfFreight=scope.row.priceOfFreight.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" placeholder="请输入运输费" />
          </template>
        </el-table-column>
        <TableCloumn v-if="form.receivingInfo==1 && type !== 'detail'" v-for="item  in tableCloumnTT" :cellOptions="item" minWidth="150px" />
        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="仓储费单价(元/天/台)" align="center" prop="unitPriceOfStorageFee" min-width="200px" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ format_thousand(scope.row.unitPriceOfStorageFee) }}</span>
          </template>
        </el-table-column>

        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="仓储费(元)" align="center" prop="priceOfStorageFee" min-width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.priceOfStorageFee" maxlength="11" @input="scope.row.priceOfStorageFee=scope.row.priceOfStorageFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" placeholder="请输入仓储费" />
          </template>
        </el-table-column>

        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="其他费用(元)" align="center" prop="otherFee" min-width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.otherFee" maxlength="11" @input="scope.row.otherFee=scope.row.otherFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" placeholder="请输入其他费用" />
          </template>
        </el-table-column>

        <el-table-column v-if="type !== 'detail'&& form.receivingInfo==1" label="总费用(元)" align="center" prop="totalFee" min-width="150PX" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ format_thousand(scope.row.totalFee) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="收车地址" align="center" prop="pickUpAddress" min-width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.pickUpAddress" placeholder="请输入收车地址" />
          </template>
        </el-table-column>

        <el-table-column label="送车地址" align="center" prop="dropOffAddress" min-width="150px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.dropOffAddress" placeholder="请输入送车地址" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <!-- 添加或修改测试单表对话框 -->
    <el-dialog title="选择车辆" :visible.sync="open" append-to-body class="form-dialog" width="70%">
      <div style="width: 90%; margin: 0 auto;">
        <el-form ref="formDig" label-position="right" :model="formDig" label-width="160px">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <el-form-item label="车牌号:" label-width="120px">
              <el-input v-model="queryParamsDig.carNo" clearable placeholder="请输入车辆归属公司" style="width: 100%;"></el-input>
            </el-form-item>
            <el-form-item label="品牌/车型/车款:" label-width="120px" style="margin-left: 20px;">
              <el-input v-model="queryParamsDig.carInFo" clearable></el-input>
            </el-form-item>
            <div style="text-align: right;margin-top: -15px;margin-left: 50px;">
              <el-button size="mini" @click="resetQueryDig">重 置</el-button>
              <el-button size="mini" type="primary" @click="handleQueryDig">查 询</el-button>
            </div>
          </div>
          <table-page ref="el-table" rowKey="id" :isSelect="true" @selectionChange="handleSelectionChange" :loading="loadingTable" :dataList="dataListTable" border :total="totalTable" :page.sync="queryParamsDig.pageNum" :limit.sync="queryParamsDig.pageSize" @setSizeCurrent="getListTable">
            <!-- 普通列插槽 -->
            <template slot="tableCol">
              <el-table-column label="车牌号" align="center" prop="carNo" min-width="100px" show-overflow-tooltip />
              <el-table-column label="车架号" align="center" prop="vinNo" min-width="150px" show-overflow-tooltip />
              <el-table-column label="品牌/车型/车款" align="center" prop="carInFo" min-width="350px" show-overflow-tooltip />
              <el-table-column label="车辆归属" align="center" prop="vehicleOwnerName" min-width="120px" show-overflow-tooltip />
              <el-table-column label="额度申请编号" align="center" prop="calcSchemeCode" min-width="200px" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span @click="goToDetail(scope.row.calcSchemeId, scope.row.processId)" style="color: #1890ff; cursor: pointer">{{ scope.row.calcSchemeCode }}</span>
                </template>
              </el-table-column>
              <el-table-column label="订单编号" align="center" prop="orderCarCode" min-width="200px" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span @click="orderDetail(scope.row)" style="color: #1890ff; cursor: pointer">{{ scope.row.orderCarCode }}</span>
                </template>
              </el-table-column>
              <el-table-column label="出租方" align="center" prop="lessorName" min-width="150px" show-overflow-tooltip />
            </template>
          </table-page>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="cancelDig">取消</el-button>
        <el-button type="primary" @click="submitForm">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import { getSelectCarListList } from "@/api/pickUpTheCar";
import TableCloumn from "@/views/finance/manage/tableColumn/index.vue";

export default {
  // 车辆信息
  name: 'carInformationJf',
  dicts: ['business_type'],
  components: {
    SearchContent,
    TableCloumn
  },
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: '',
    },
  },
  computed: {
    tableCloumnGLS() {
      return [
        {
          label: "公里数",
          prop: "kilometres",
          type: "input",
          width: "150px",
          watch: ({ val, row }) => {
            this.$set(row, 'priceOfFreight', row.kilometres * row.unitPriceOfFreight)
          },
        }]
    },
    tableCloumnTT() {
      return [
        {
          label: "仓储天数",
          prop: "daysOfStorage",
          type: "input",
          width: "150px",
          watch: ({ val, row }) => {
            this.$set(row, 'priceOfStorageFee', row.daysOfStorage * row.unitPriceOfStorageFee)
          },
        }]
    },
    form: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
    type() {
      let status
      switch (this.state) {
        case 'write':
          status = 'edit'
          break
        case 'disabled':
          status = 'detail'
          break
        case 'readonly':
          status = 'detail'
          break
        case 'detail':
          status = 'detail'
          break
        case 'edit':
          status = 'edit'
        case 'add':
          status = 'add'
          break
      }
      return status
    },
    totalPrice() {
      return this.form.carList?.length > 0 ? this.form.carList.reduce((acc, item) => acc + Number(item.totalFee), 0) : 0
    },
  },
  data() {
    return {
      dataListTable: [],
      multipleSelection: [],
      totalTable: 0,
      loadingTable: false,
      formDig: {},
      open: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParamsDig: {
        pageNum: 1,
        pageSize: 10,
      },
      GPSlist: [
        {
          label: '正常',
          value: 1
        },
        {
          label: '异常',
          value: 2
        }
      ],
      idList: []
    };
  },
  watch: {
    dataListTable: {
      handler(Val) {
        this.$nextTick(() => {
          this.$refs['el-table']?.table_clearSelection()
          Val?.forEach((v) => {
            this.idList?.forEach((j) => {
              if (
                v.id == j
              ) {
                this.$refs['el-table'].table_toggleRowSelection(v, true)
              }
            });
          });
        });
      },
      immediate: true, // 立即生效
      deep: true  //监听对象或数组的时候，要用到深度监听
    },
    'form.carList': {
      handler(val) {
        val?.forEach((v, i) => {
          if (v.priceOfFreight && v.priceOfStorageFee && v.serviceCharge && v.otherFee) {
            this.$set(v, 'totalFee', Number(v.priceOfFreight) + Number(v.priceOfStorageFee) + Number(v.serviceCharge) + Number(v.otherFee))
          }
        })
      },
      deep: true,
      immediate: true
    },
  },
  created() {
  },
  methods: {
    changeValue(type) {
      // if (this.form.aaaa || this.form.bbbb || this.form.cccc || this.form.dddd) {
      if (type == 1) {
        if (this.form.aaaa) {
          this.form.carList?.forEach((v, i) => {
            this.$set(v, 'kilometres', this.form.aaaa)
          })
          this.$message({
            type: 'success',
            message: '一键填入成功，请查看车辆列表数据'
          });
        } else {
          this.$message({
            type: 'error',
            message: '请填入数据'
          });
        }
      } else if (type == 2) {
        if (this.form.bbbb) {
          this.form.carList?.forEach(v => {
            this.$set(v, 'daysOfStorage', this.form.bbbb)
          })
          this.$message({
            type: 'success',
            message: '一键填入成功，请查看车辆列表数据'
          });
        } else {
          this.$message({
            type: 'error',
            message: '请填入数据'
          });
        }
      } else if (type == 3) {
        if (this.form.cccc) {
          this.form.carList?.forEach(v => {
            this.$set(v, 'pickUpAddress', this.form.cccc)
          })
          this.$message({
            type: 'success',
            message: '一键填入成功，请查看车辆列表数据'
          });
        } else {
          this.$message({
            type: 'error',
            message: '请填入数据'
          });
        }
      } else {
        if (this.form.dddd) {
          this.form.carList?.forEach(v => {
            this.$set(v, 'dropOffAddress', this.form.dddd)
          })
          this.$message({
            type: 'success',
            message: '一键填入成功，请查看车辆列表数据'
          });
        } else {
          this.$message({
            type: 'error',
            message: '请填入数据'
          });
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.open = false
      let newArray = this.multipleSelection.map(v => {
        return {
          ...v
        }
      })
      this.idList = this.multipleSelection.map(v => v.id)
      this.form.carList = JSON.parse(JSON.stringify(newArray))
    },
    // 取消按钮
    cancelDig() { this.open = false },
    /**
     *重置
     */
    resetQueryDig() {
      this.queryParamsDig = {
        pageNum: 1,
        pageSize: 10,
      }
      this.getListTable()
    },
    /**
     *搜索
     */
    handleQueryDig() {
      this.getListTable()
    },
    /**
     *弹窗接口
     */
    async getListTable() {
      this.loadingTable = true;
      let data = {
        ...this.queryParamsDig,
        backCarId: this.$route.query.backCarId
      }
      try {
        let res = await getSelectCarListList(data)
        const { rows, total } = res;
        this.dataListTable = rows;
        // this.dataListTable = [
        //   {
        //     "manageId": 0,
        //     "warningId": 0,
        //     "carId": 0,
        //     "carNo": "123",
        //     "vinNo": "123",
        //     "carInFo": "123",
        //     "vehicleOwnerCode": "",
        //     "vehicleOwnerName": "",
        //     "calcSchemeId": 0,
        //     "calcSchemeCode": "",
        //     "orderCarId": 0,
        //     "orderCarCode": "",
        //     "lessorId": 0,
        //     "lessorName": "",
        //     "businessType": 0,
        //     "orderSubmitter": "",
        //     "gpsStatus": 1,
        //     "id": 0,
        //     "backCarId": 0,
        //     "serviceCharge": 0,
        //     "kilometres": 0,
        //     "unitPriceOfFreight": 1,
        //     "priceOfFreight": 0,
        //     "daysOfStorage": 0,
        //     "unitPriceOfStorageFee": 1,
        //     "priceOfStorageFee": 0,
        //     "otherFee": 0,
        //     "totalFee": 0,
        //     "pickUpAddress": "",
        //     "dropOffAddress": ""
        //   }
        // ]
        this.totalTable = total;
        this.loadingTable = false;
      } catch (error) {

      }
    },
    // 多选按钮
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**
     * 选择载具
     */
    selectCar() {
      this.getListTable()
      this.open = true
    },
    /**
     * 删除车辆功能
     */
    selectCustomer(row, index) {
      this.$confirm('确认删除该车辆?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.carList.splice(index, 1)
        if (this.form.carList.length == 0) {
          this.idList = []
          this.$set(this.form, 'aaaa', '')
          this.$set(this.form, 'bbbb', '')
          this.$set(this.form, 'cccc', '')
          this.$set(this.form, 'dddd', '')
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getList() { },
    /**
     *额度跳转
     */
    goToDetail(calcSchemeId) {
      this._toPage({
        path: '/quota/ApplyDetails',
        query: {
          calcSchemeId,
        },
      })
    },
    /**
     *订单详情
     */
    orderDetail(row) {
      this._toPage({
        name: "SuborderDetail",
        query: {
          id: row.orderCarId,
          orderCarCode: row.orderCarCode,
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.statisticInfo {
  color: #464646;
  font-size: 14px;
  margin-right: 10px;

  span {
    color: #1884ff;
  }
}
</style>
